<?php

/*
 * Table/SiteDocTable.php
 */

namespace RHX\Model\Table;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\ResultSet\ResultSet;
use RHX\Model\Object\SiteDoc;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;

class SiteDocTable extends AbstractTableGateway {

    protected $table = 'rh_site_doc';

    public function __construct(Adapter $adapter) {
	$this->adapter			 = $adapter;
	$this->resultSetPrototype	 = new ResultSet();
	$this->resultSetPrototype->setArrayObjectPrototype(new SiteDoc($adapter));
	$this->initialize();
    }

    public function getAll() {
	return $this->select();
    }

    public function get($id) {
	$row = $this->select(array('id' => $id))
		->current();
	if (!$row)
	    throw new \Exception("Impossible de trouver #$id");

	return $row;
    }

    public function save(SiteDoc $siteDoc) {
	$data	 = array(	    
	    'site_id'		 => $siteDoc->site_id,
	    'path'		 => $siteDoc->path,
            'libelle'		 => $siteDoc->libelle
	);
        
	$id	 = (int) $siteDoc->id;
	if ($id == 0){
	    $this->insert($data);
	    return $this->getLastInsertValue();
	}
	elseif ($this->get($id)){
	    $this->update($data, array('id' => $id));
	    return $id;
	}
	else{
	    throw new \Exception("Impossible de trouver #$id");
	}
    }

    public function executeQuery($sql) {
	return $this->adapter
			->query($sql)
			->execute();
    }
    
    public function getBySite($siteId){
        return $this->select(function(Select $select) use($siteId) {
			    $where = new Where();
			    $where->equalTo('site_id', $siteId);			    
			    $select->where($where);
			});
    }
    
    public function erase($id) {
        $this->delete(array('id' => $id));
    }
    
    /* Récupérer le dernier ID des enregistrements
     * @return int
     */
    public function getMaxId(){
        $sql = 'select MAX(id) as max_id FROM rh_site_doc ';
        $res = $this->executeQuery($sql)->current();
        $max_id = $res['max_id']; 
        
        return (int) $max_id;
    }
}

?>
